/**
 * 配置元数据系统 (服务器端)
 * 通过元数据描述配置结构，实现动态界面生成
 * 与前端的ConfigSchema保持同步
 */

// === 字段类型定义 ===
export type FieldType = 
  | 'string' 
  | 'number' 
  | 'boolean' 
  | 'select' 
  | 'multiSelect'
  | 'array' 
  | 'object' 
  | 'json'
  | 'textarea'
  | 'color'
  | 'file'
  | 'date'
  | 'range'
  | 'tags'
  | 'skillSelector'
  | 'attributeEditor'
  | 'qualityRange'
  | 'emoji'

// === 字段验证规则 ===
export interface ValidationRule {
  type: 'required' | 'min' | 'max' | 'pattern' | 'custom'
  value?: any
  message: string
  validator?: string // 自定义验证函数名
}

// === 字段选项 ===
export interface FieldOption {
  label: string
  value: any
  disabled?: boolean
  description?: string
  icon?: string
}

// === 字段元数据 ===
export interface FieldSchema {
  /** 字段键名 */
  key: string
  /** 显示标签 */
  label: string
  /** 字段类型 */
  type: FieldType
  /** 是否必填 */
  required?: boolean
  /** 默认值 */
  defaultValue?: any
  /** 字段描述 */
  description?: string
  /** 占位符 */
  placeholder?: string
  /** 验证规则 */
  rules?: ValidationRule[]
  /** 选项列表（select/multiSelect类型使用） */
  options?: FieldOption[]
  /** 选项数据源（动态选项） */
  optionsSource?: string
  /** 最小值（number/range类型） */
  min?: number
  /** 最大值（number/range类型） */
  max?: number
  /** 步长（number类型） */
  step?: number
  /** 数组项的schema（array类型使用） */
  itemSchema?: FieldSchema
  /** 对象属性的schema（object类型使用） */
  properties?: Record<string, FieldSchema>
  /** 是否可见 */
  visible?: boolean | string // 可以是表达式
  /** 是否禁用 */
  disabled?: boolean | string
  /** 字段分组 */
  group?: string
  /** 排序权重 */
  order?: number
  /** 自定义渲染组件 */
  component?: string
  /** 组件属性 */
  componentProps?: Record<string, any>
  /** 依赖字段 */
  dependencies?: string[]
  /** 条件显示逻辑 */
  showWhen?: {
    field: string
    operator: '==' | '!=' | '>' | '<' | 'contains' | 'in'
    value: any
  }[]
}

// === 配置表单分组 ===
export interface FormGroup {
  key: string
  label: string
  description?: string
  icon?: string
  order?: number
  collapsed?: boolean
}

// === 配置Schema ===
export interface ConfigSchema {
  /** Schema版本 */
  version: string
  /** 配置类型名称 */
  type: string
  /** 配置名称 */
  name: string
  /** 配置描述 */
  description: string
  /** 字段列表 */
  fields: FieldSchema[]
  /** 分组配置 */
  groups?: FormGroup[]
  /** 全局验证规则 */
  globalValidation?: ValidationRule[]
  /** 支持的操作 */
  actions?: {
    create?: boolean
    edit?: boolean
    delete?: boolean
    duplicate?: boolean
    export?: boolean
    import?: boolean
  }
  /** 列表显示配置 */
  listConfig?: {
    /** 主要显示字段 */
    primaryField: string
    /** 次要显示字段 */
    secondaryFields: string[]
    /** 状态字段 */
    statusField?: string
    /** 搜索字段 */
    searchFields: string[]
    /** 排序字段 */
    sortFields: string[]
  }
  /** 预览配置 */
  previewConfig?: {
    /** 预览模板 */
    template: string
    /** 预览字段 */
    fields: string[]
  }
}

// === 内置配置Schema定义 ===
export const EquipmentConfigSchema: ConfigSchema = {
  version: "1.0.0",
  type: "equipment",
  name: "装备配置",
  description: "游戏装备模板配置",
  fields: [
    {
      key: "id",
      label: "装备ID",
      type: "string",
      required: true,
      description: "装备的唯一标识符",
      placeholder: "输入唯一的装备ID",
      rules: [
        { type: "required", message: "装备ID不能为空" },
        { type: "pattern", value: "^[a-zA-Z0-9_-]+$", message: "ID只能包含字母、数字、下划线和连字符" }
      ],
      group: "basic",
      order: 1
    },
    {
      key: "name",
      label: "装备名称",
      type: "string",
      required: true,
      placeholder: "输入装备名称",
      group: "basic",
      order: 2
    },
    {
      key: "emoji",
      label: "表情符号",
      type: "emoji",
      defaultValue: "⚔️",
      description: "装备的表情符号图标",
      group: "basic",
      order: 3
    },
    {
      key: "sys",
      label: "体系",
      type: "select",
      required: true,
      options: [
        { label: "现代", value: "现代" },
        { label: "古典", value: "古典" },
        { label: "未来", value: "未来" }
      ],
      group: "basic",
      order: 4
    },
    {
      key: "type",
      label: "类型",
      type: "select",
      required: true,
      options: [
        { label: "武器", value: "武器" },
        { label: "防具", value: "防具" },
        { label: "饰品", value: "饰品" }
      ],
      group: "basic",
      order: 5
    },
    {
      key: "job",
      label: "职业",
      type: "select",
      required: true,
      options: [
        { label: "血骑士", value: "血骑士" },
        { label: "圣牧师", value: "圣牧师" },
        { label: "影刺客", value: "影刺客" },
        { label: "通用", value: "通用" }
      ],
      group: "basic",
      order: 6
    },
    {
      key: "solt",
      label: "装备部位",
      type: "select",
      required: true,
      options: [
        { label: "主手", value: "主手" },
        { label: "副手", value: "副手" },
        { label: "头部", value: "头部" },
        { label: "胸部", value: "胸部" },
        { label: "腿部", value: "腿部" },
        { label: "脚部", value: "脚部" },
        { label: "手部", value: "手部" },
        { label: "戒指", value: "戒指" },
        { label: "项链", value: "项链" }
      ],
      group: "basic",
      order: 7
    },
    {
      key: "desc",
      label: "描述",
      type: "textarea",
      placeholder: "输入装备描述",
      group: "basic",
      order: 8
    },
    {
      key: "quality",
      label: "品质范围",
      type: "qualityRange",
      defaultValue: { min: 1, max: 5 },
      description: "装备的品质等级范围",
      group: "quality",
      order: 10
    },
    {
      key: "baseAttributes",
      label: "基础属性",
      type: "attributeEditor",
      defaultValue: [],
      description: "装备的基础属性配置",
      group: "attributes",
      order: 20
    },
    {
      key: "skillPools",
      label: "技能池",
      type: "object",
      description: "装备的技能配置",
      properties: {
        inherent: {
          key: "inherent",
          label: "固有技能",
          type: "skillSelector",
          defaultValue: []
        },
        enchantable: {
          key: "enchantable",
          label: "可附魔技能",
          type: "array",
          itemSchema: {
            key: "enchantableSkill",
            label: "附魔技能",
            type: "object",
            properties: {
              skill: {
                key: "skill",
                label: "技能",
                type: "skillSelector",
                required: true
              },
              weight: {
                key: "weight",
                label: "权重",
                type: "number",
                min: 1,
                max: 100,
                defaultValue: 1
              }
            }
          }
        }
      },
      group: "skills",
      order: 30
    },
    {
      key: "enabled",
      label: "启用状态",
      type: "boolean",
      defaultValue: true,
      group: "metadata",
      order: 40
    },
    {
      key: "tags",
      label: "标签",
      type: "tags",
      defaultValue: [],
      description: "用于分类和搜索的标签",
      group: "metadata",
      order: 41
    }
  ],
  groups: [
    { key: "basic", label: "基础信息", icon: "info", order: 1 },
    { key: "quality", label: "品质配置", icon: "star", order: 2 },
    { key: "attributes", label: "属性配置", icon: "trending-up", order: 3 },
    { key: "skills", label: "技能配置", icon: "zap", order: 4 },
    { key: "metadata", label: "元数据", icon: "tag", order: 5 }
  ],
  actions: {
    create: true,
    edit: true,
    delete: true,
    duplicate: true,
    export: true,
    import: true
  },
  listConfig: {
    primaryField: "name",
    secondaryFields: ["job", "type", "sys"],
    statusField: "enabled",
    searchFields: ["name", "id", "desc"],
    sortFields: ["name", "job", "type", "lastModified"]
  },
  previewConfig: {
    template: "equipment-preview",
    fields: ["name", "emoji", "desc", "quality", "baseAttributes"]
  }
}

export const SkillConfigSchema: ConfigSchema = {
  version: "1.0.0",
  type: "skill",
  name: "技能配置",
  description: "游戏技能配置",
  fields: [
    {
      key: "skillId",
      label: "技能ID",
      type: "string",
      required: true,
      placeholder: "输入唯一的技能ID",
      group: "basic",
      order: 1
    },
    {
      key: "name",
      label: "技能名称",
      type: "string",
      required: true,
      placeholder: "输入技能名称",
      group: "basic",
      order: 2
    },
    {
      key: "description",
      label: "技能描述",
      type: "textarea",
      placeholder: "输入技能描述",
      group: "basic",
      order: 3
    },
    {
      key: "type",
      label: "技能类型",
      type: "select",
      options: [
        { label: "主动技能", value: "active" },
        { label: "被动技能", value: "passive" },
        { label: "光环技能", value: "aura" }
      ],
      group: "basic",
      order: 4
    },
    {
      key: "quality",
      label: "技能品质",
      type: "select",
      options: [
        { label: "普通", value: 1 },
        { label: "优秀", value: 2 },
        { label: "稀有", value: 3 },
        { label: "史诗", value: 4 },
        { label: "传说", value: 5 }
      ],
      group: "basic",
      order: 5
    },
    {
      key: "cooldown",
      label: "冷却时间",
      type: "number",
      min: 0,
      defaultValue: 0,
      description: "技能冷却回合数",
      group: "mechanics",
      order: 10
    },
    {
      key: "maxLevel",
      label: "最高等级",
      type: "number",
      min: 1,
      max: 20,
      defaultValue: 1,
      group: "mechanics",
      order: 11
    }
  ],
  groups: [
    { key: "basic", label: "基础信息", order: 1 },
    { key: "mechanics", label: "技能机制", order: 2 },
    { key: "effects", label: "技能效果", order: 3 }
  ],
  actions: {
    create: true,
    edit: true,
    delete: true,
    duplicate: true,
    export: true
  },
  listConfig: {
    primaryField: "name",
    secondaryFields: ["type", "quality"],
    searchFields: ["name", "skillId", "description"],
    sortFields: ["name", "type", "quality"]
  }
}

// === Schema管理器 ===
export class ConfigSchemaManager {
  private schemas = new Map<string, ConfigSchema>()
  
  constructor() {
    // 注册内置schema
    this.registerSchema(EquipmentConfigSchema)
    this.registerSchema(SkillConfigSchema)
  }
  
  /**
   * 注册配置Schema
   */
  registerSchema(schema: ConfigSchema): void {
    this.schemas.set(schema.type, schema)
  }
  
  /**
   * 获取配置Schema
   */
  getSchema(type: string): ConfigSchema | undefined {
    return this.schemas.get(type)
  }
  
  /**
   * 获取所有注册的Schema
   */
  getAllSchemas(): ConfigSchema[] {
    return Array.from(this.schemas.values())
  }
  
  /**
   * 从TypeScript类型生成Schema（未来功能）
   */
  generateSchemaFromType(typeName: string): ConfigSchema {
    // TODO: 实现TypeScript类型到Schema的转换
    throw new Error('Not implemented yet')
  }
  
  /**
   * 验证配置数据是否符合Schema
   */
  validateData(type: string, data: any): { valid: boolean, errors: string[] } {
    const schema = this.getSchema(type)
    if (!schema) {
      return { valid: false, errors: [`未找到类型 ${type} 的Schema`] }
    }
    
    const errors: string[] = []
    
    // 验证必填字段
    for (const field of schema.fields) {
      if (field.required && (data[field.key] === undefined || data[field.key] === null || data[field.key] === '')) {
        errors.push(`字段 ${field.label} 不能为空`)
      }
      
      // 验证字段规则
      if (field.rules && data[field.key] !== undefined) {
        for (const rule of field.rules) {
          const fieldValue = data[field.key]
          
          switch (rule.type) {
            case 'pattern':
              if (typeof fieldValue === 'string' && rule.value) {
                const regex = new RegExp(rule.value)
                if (!regex.test(fieldValue)) {
                  errors.push(rule.message)
                }
              }
              break
            case 'min':
              if (typeof fieldValue === 'number' && fieldValue < rule.value) {
                errors.push(rule.message)
              }
              break
            case 'max':
              if (typeof fieldValue === 'number' && fieldValue > rule.value) {
                errors.push(rule.message)
              }
              break
          }
        }
      }
    }
    
    return { valid: errors.length === 0, errors }
  }
}

// 导出全局Schema管理器实例
export const schemaManager = new ConfigSchemaManager()
